//
//  TodoView.swift
//  NaiCha
//
//  Created by 唐安坤 on 2024/9/19.
//

import SwiftUI

struct TodoView: View {
    @Environment(\.presentationMode) var presentationMode
    @State var todo:String = ""
    @State var priority: PriorityEnum = .normal
    @State var isShowAlert = false
    var backBlock: ((Todos) -> Void)?
    
    init( backBlock: ( (Todos) -> Void)? = nil) {
  
        self.backBlock = backBlock
    }
    
    var body: some View {
        NavigationStack {
            VStack{
                HStack{
                    Text("新增代办")
                        .font(.title.bold())
                        .padding([.leading])
                    Spacer()
                }
                
                TextField("请输入代办任务", text: $todo)
                    .textFieldStyle(.roundedBorder)
                    .padding([.leading, .trailing])
                
                HStack{
                    Text("优先级").padding()
                    Spacer()
                }
                
                Picker.init(selection: $priority) {
                    ForEach(PriorityEnum.allCases, id: \.self){ priority in
                        Text(priority.name)
                    }
                } label: {
                    
                }.padding([.leading, .trailing])
                .pickerStyle(.segmented)

                
                Button(action: {
                   
                    isShowAlert = todo.count == 0
                    if !isShowAlert{
                        print(todo,priority.name)
                        
                        if let block = backBlock {
                            block(Todos.init(todoName: todo, priority: priority))
                        }
                        presentationMode.wrappedValue.dismiss()
                    }
                }, label: {
                    Text("保存")
                }).alert(isPresented: $isShowAlert, content: {
                    Alert(title: Text("请输入代办名称"), message: nil, dismissButton: Alert.Button.cancel())
                })
                .frame(maxWidth: .infinity,maxHeight: 40)
                .foregroundColor(.white)
                .background(.purple)
                .clipShape(RoundedRectangle(cornerRadius: 5))
                .padding()
              
            }.toolbar(content: {
                Image(systemName: "x.circle")
                    .foregroundColor(.gray)
                    .onTapGesture {
                        presentationMode.wrappedValue.dismiss()
                }
            })
            
        }.presentationDetents([.large,.fraction(0.5)])
       
    }
}

#Preview {
    TodoView { todo in
        
    }
}
